﻿using HotFolderServiceInterface;
using NLog;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.Composition;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HotFolderTask
{
    [Export(typeof(IHotFolderType))]
    public class FTPUploader : IHotFolderType
    {
        ILogger logger;
        [ImportingConstructor]
        public FTPUploader([Import("Logger")]ILogger logger)
        {
            this.logger = logger;
        }

        public string HotFolderTypeName
        {
            get { return "FTPUploader"; }
        }


        public void Execute(String name, String path, NameValueCollection settings)
        {

            logger.Trace("executing ftpuploader");
            String host = "ftp://" + settings["FTPHost"];
            String username = settings["Username"];
            String password = settings["Password"];
            String remotefolder = settings["RemoteFolder"];
            UploadFile(host, remotefolder, path, username, password);

        }

        /// <summary>
        /// Methods to upload file to FTP Server
        /// </summary>
        /// <param name="_FileName">local source file name</param>
        /// <param name="_UploadPath">Upload FTP path including Host name</param>
        /// <param name="_FTPUser">FTP login username</param>
        /// <param name="_FTPPass">FTP login password</param>
        public void UploadFile(String host, String remotefolder, string _FileName, string _FTPUser, string _FTPPass)
        {
            System.IO.FileInfo _FileInfo = new System.IO.FileInfo(_FileName);

            // Create FtpWebRequest object from the Uri provided
            System.Net.FtpWebRequest _FtpWebRequest = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(new Uri(host + remotefolder + _FileInfo.Name));
            

            // Provide the WebPermission Credintials
            _FtpWebRequest.Credentials = new System.Net.NetworkCredential(_FTPUser, _FTPPass);

            // By default KeepAlive is true, where the control connection is not closed
            // after a command is executed.
            _FtpWebRequest.KeepAlive = false;

            // set timeout for 20 seconds
            _FtpWebRequest.Timeout = 20000;

            // Specify the command to be executed.
            _FtpWebRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile;

            // Specify the data transfer type.
            _FtpWebRequest.UseBinary = true;

            // Notify the server about the size of the uploaded file
            _FtpWebRequest.ContentLength = _FileInfo.Length;

            // The buffer size is set to 2kb
            int buffLength = 2048;
            byte[] buff = new byte[buffLength];

            // Opens a file stream (System.IO.FileStream) to read the file to be uploaded
            using (System.IO.FileStream _FileStream = _FileInfo.OpenRead())
            {



                try
                {
                    // Stream to which the file to be upload is written
                    using (System.IO.Stream _Stream = _FtpWebRequest.GetRequestStream())
                    {
                        // Read from the file stream 2kb at a time
                        int contentLen = _FileStream.Read(buff, 0, buffLength);

                        // Till Stream content ends
                        while (contentLen != 0)
                        {
                            // Write Content from the file stream to the FTP Upload Stream
                            _Stream.Write(buff, 0, contentLen);
                            contentLen = _FileStream.Read(buff, 0, buffLength);
                        }

                        // Close the file stream and the Request Stream
                        
                    }

                   
                }
                catch (Exception ex)
                {
                    logger.Exception(ex);
                }
            }
            
        }



    }
}
